package com.iaiai.calendar.activity;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iaiai.calendar.util.DateUtil;
import com.iaiai.calendar.util.LunarCalendar;
import com.iaiai.calendar.util.SolarTerms;
import com.iaiai.calendar.util.Utils;

/**
 * 
 * <p>
 * Title: CalendarGridView.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-1-1
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class CalendarGridView extends LinearLayout {

	private Context mContext;

	private Calendar calendar = Calendar.getInstance(); // 当前显示的日历

	private int month = 0; // 当前月

	private LinearLayout currLinearLayout; // 当前选择的按钮

	private Date currDate = new Date(); // 当前日期

	public CalendarGridView(Context context, Calendar calendar) {
		super(context);
		mContext = context;
		this.calendar.setTime(calendar.getTime());
		month = DateUtil.getMonth(calendar.getTime());

		init();
	}

	public Calendar getCalendar() {
		return calendar;
	}

	private void init() {
		setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		setOrientation(LinearLayout.VERTICAL);

		try {
			setView(getData()); // 显示数据
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 显示内容
	 * 
	 * @param list
	 *            数据
	 */
	private void setView(final List<Date> list) {
		if (list == null || list.size() <= 0)
			return;

		WindowManager windowManager = ((Activity) mContext).getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		int width = display.getWidth() / 7;

		LinearLayout layout = new LinearLayout(mContext);
		layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT, 1));

		for (int i = 0; i < list.size(); i++) {
			final int index = i;
			if (i != 0 && i % 7 == 0) {
				this.addView(layout);
				layout = new LinearLayout(mContext);
				layout.setLayoutParams(new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1));
			}
			final LinearLayout ll = new LinearLayout(mContext);
			ll.setLayoutParams(new LayoutParams(width,
					LayoutParams.FILL_PARENT, 1));
			ll.setOrientation(LinearLayout.VERTICAL);

			final LinearLayout bg = new LinearLayout(mContext);
			bg.setLayoutParams(new LayoutParams(width,
					LayoutParams.FILL_PARENT, 1));
			bg.setOrientation(LinearLayout.VERTICAL);
			ll.addView(bg);

			final TextView btn = new TextView(mContext);
			btn.setOnTouchListener((OnTouchListener) mContext);
			btn.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT, 1));
			btn.setWidth(width); // 设置宽度
			btn.setTextSize(Utils.pxTodip(mContext, 20));
			btn.setText(String.valueOf(list.get(i).getDate()));
			btn.setGravity(Gravity.CENTER | Gravity.BOTTOM);

			// 判断是否是今天，如果是则设置背景
			if (list.get(i).getYear() == currDate.getYear()
					&& list.get(i).getMonth() == currDate.getMonth()
					&& list.get(i).getDay() == currDate.getDay()
					&& list.get(i).getDate() == currDate.getDate()) {
				bg.setBackgroundDrawable(mContext.getResources().getDrawable(
						R.drawable.typeb_calendar_today));
			}

			btn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					ll.setBackgroundDrawable(mContext.getResources()
							.getDrawable(R.drawable.sel_bg));

					if (currLinearLayout != null) {
						currLinearLayout.setBackgroundColor(Color.TRANSPARENT);
					}
					currLinearLayout = ll;

					Intent intent = new Intent(mContext, DayActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("day",
							DateUtil.formatDate(list.get(index)));
					intent.putExtras(bundle);
					mContext.startActivity(intent);
				}
			});

			// 计算阴历是否是初一，如果是标记为红色字体
			LunarCalendar lunar = new LunarCalendar(list.get(i));
			if (lunar.getMonth() == 1 && lunar.getDay() == 1) {
				btn.setTextColor(Color.RED);
			} else {
				if (month == DateUtil.getMonth(list.get(i))) {
					btn.setTextColor(Color.WHITE);
				} else {
					btn.setTextColor(Color.GRAY);
				}
			}

			bg.addView(btn);

			// 计算节气
			String solarTerms = SolarTerms.getSolarTerms(list.get(i));
			TextView textView = new TextView(mContext);
			textView.setOnTouchListener((OnTouchListener) mContext);
			textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT, 1));
			textView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					ll.setBackgroundDrawable(mContext.getResources()
							.getDrawable(R.drawable.sel_bg));

					if (currLinearLayout != null) {
						currLinearLayout.setBackgroundColor(Color.TRANSPARENT);
					}
					currLinearLayout = ll;
					
					Intent intent = new Intent(mContext, DayActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("day",
							DateUtil.formatDate(list.get(index)));
					intent.putExtras(bundle);
					mContext.startActivity(intent);
				}
			});
			if (month == DateUtil.getMonth(list.get(i))) {
				textView.setTextColor(Color.WHITE);
			} else {
				textView.setTextColor(Color.GRAY);
			}
			textView.setGravity(Gravity.CENTER | Gravity.TOP);
			if (solarTerms != null && solarTerms.length() > 0) { // 显示节气
				textView.setText(solarTerms);
			} else { // 显示农历
				textView.setText(lunar.getLunarDay());
			}
			bg.addView(textView);

			layout.addView(ll);
		}
		this.addView(layout);
	}

	/**
	 * 获得数据
	 * 
	 * @return
	 * @throws ParseException
	 */
	private List<Date> getData() throws ParseException {
		int month = DateUtil.getMonth(calendar.getTime()) + 1;
		int year = DateUtil.getYear(calendar.getTime());
		Calendar startDate = Calendar.getInstance();
		startDate
				.setTime(DateUtil.getFirstDayOfWeek(DateUtil
						.formatDate(DateUtil.getYear(calendar.getTime()) + "-"
								+ (DateUtil.getMonth(calendar.getTime()) + 1)
								+ "-01"))); // 开始日期
		startDate.add(Calendar.DATE, -1);
		Calendar endDate = Calendar.getInstance();
		endDate.setTime(DateUtil.getFirstDayOfWeek(DateUtil.formatDate(year
				+ "-" + month + "-" + DateUtil.getDaysByMonth(year, month))));
		endDate.add(Calendar.DATE, 6);

		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate.getTime());

		List<Date> list = new ArrayList<Date>();
		while (DateUtil.getBetweenDays(DateUtil.formatDate(cal.getTime()),
				DateUtil.formatDate(endDate.getTime())) < 0) {
			list.add(cal.getTime());
			cal.add(Calendar.DATE, 1);
		}

		// 如果只有五行则再添加一行
		if (list.size() <= 35) {
			if (DateUtil.getMonth(startDate.getTime()) == DateUtil
					.getMonth(calendar.getTime())) { // 如果开始日期的月是一样的，则前面再加一个星期
				cal.setTime(startDate.getTime());
				cal.add(Calendar.DATE, -1);
				startDate.setTime(DateUtil.getFirstDayOfWeek(cal.getTime()));
				startDate.add(Calendar.DATE, -1);

				List<Date> lt = new ArrayList<Date>();
				for (int i = 0; i < 7; i++) {
					lt.add(startDate.getTime());
					startDate.add(Calendar.DATE, 1);
				}
				list.addAll(0, lt);
			} else { // 如果开始日期不是这个月，则再后面添加一个星期
				List<Date> lt = new ArrayList<Date>();
				for (int i = 0; i < 7; i++) {
					lt.add(endDate.getTime());
					endDate.add(Calendar.DATE, 1);
				}
				list.addAll(lt);
			}
		}

		return list;
	}

}
